//var jsonElement = document.getElementById('json');
var formElement = document.getElementById('formio');
//var subJSON = document.getElementById('subjson');

var action=$('#action').val();
var formdata=$('#formdata').val();

var compts=[];
if(action=="update"){
	compts=JSON.parse(formdata);
	compts= compts.components;
}
var builder = new Formio.FormBuilder(document.getElementById("builder"), {
	display : 'form',
	components : compts
});

var onForm = function(form) {
	form.on('change', function() {
		subJSON.innerHTML = '';
		subJSON.appendChild(document.createTextNode(JSON.stringify(
				form.submission, null, 4)));
	});
};



var setDisplay = function(display) {
	builder.setDisplay(display).then(
			function(instance) {
				instance.on('change', function(form) {
					if (form.components) {
//						formElement.innerHTML = '';
//						jsonElement.innerHTML = '';
//						jsonElement.appendChild(document.createTextNode(JSON
//								.stringify(form, null, 4)));
//						Formio.createForm(formElement, form).then(onForm);
					}
				});
			});
};

// Handle the form selection.
var formSelect = document.getElementById('form-select');
formSelect.addEventListener("change", function() {
	setDisplay(this.value);
});
setDisplay('form');

function getFormData(){
	var schemaJson=builder.form;
	schemaJson.id=$('#id').val();
	schemaJson.name=$('#name').val();
	schemaJson.description=$('#description').val();
	return schemaJson;
	
}

function warning(info){
	var htm = $('#warningtpl').html();
	var newhtm = htm.replace(/\${text}/,info);
	$('#warning').html(newhtm);
}

//save
$('#save').on('click', function(e) {
	var schemaJson=getFormData();
	$.ajax({
		type : "POST",
		url : "/form/save",
		contentType : "application/json; charset=utf-8",
		data : JSON.stringify(schemaJson),
		dataType : "json",
		success : function(message) {
			warning("ok")
		},
		error : function(message) {
			warning("failed")
			console.log(message);
		}
	});
});



//view
$('#preview').on('click', function(e) {
	var schemaJson=getFormData();
	$.ajax({
		type : "POST",
		url : "/form/save",
		contentType : "application/json; charset=utf-8",
		data : JSON.stringify(schemaJson),
		dataType : "json",
		success : function(message) {
			window.open("/view/"+message.id,"_blank");
		},
		error : function(message) {
			warning("failed")
		}
	});
});